package cn.biplam.front.page;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.biplam.common.tools.DEBUG;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.front.html.HtmlPage;
import cn.biplam.front.template.main.LoginForm;
import cn.biplam.front.template.main.MainImport;

public class Login{
	private HttpServletRequest request=null;
	private HttpServletResponse response=null;
	private static final boolean debug=false;

	/**
	 * 构造方法
	 * @param request
	 * @param response
	 */
	public Login(HttpServletRequest request, HttpServletResponse response){
		this.request=request;
		this.response=response;
	}

	/**
	 * 返回页面的HTML
	 * @throws ErrorMessage 
	 */
	public void draw() throws ErrorMessage{
		if(debug)
			DEBUG.println("Remote Addr="+request.getRemoteAddr()
					+"\tHost="+request.getRemoteHost()+",Port="+request.getRemotePort()
			);

		Cookie[] cks = request.getCookies();
		if(cks!=null){
			Cookie ck=null;
			for(Cookie ite:cks){
				if(ite.getName().equals("userinfo")){
					ck=ite;
				}
			}
			if(ck!=null){
				if(debug)
					DEBUG.print("发现Cookie");
				String sHomeUrl = request.getContextPath();
				String[] nv=ck.getValue().split(",");
				String userName=nv[0];
				String userPassword=nv[1];
				String str=sHomeUrl+"/LoginDo.bi?userName="+userName+"&userPassword="+userPassword;
				try {
					response.sendRedirect(str);
				} catch (IOException e) {
					throw new ErrorMessage(e,"Cookie redirect failed!");
				}
				if(debug)
					DEBUG.println("，转自动登陆:"+str);
				return;
			}
		}


		HtmlPage loginPage = new HtmlPage("用户登陆");
		String sHomeUrl = request.getContextPath();
		new MainImport().get(loginPage,sHomeUrl);
		try {
			this.response.setContentType("text/html"); 
			PrintWriter out = new PrintWriter (this.response.getOutputStream());
			loginPage.put(new LoginForm().get(request.getContextPath()));
			out.print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
			out.print(loginPage.draw());
			out.close();
		} catch(ErrorMessage e){
			throw e;
		} catch (Exception e) {
			throw new ErrorMessage(e);
		}
	}

}
